package com.test.pusher;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AudioChannel {

    private int sampleRateInHz = 44100;
    private int channels = 2;
    private Pusher mPusher;
    private AudioRecord audioRecord;
    private final int inputSamples;
    private boolean isLive;
    private ExecutorService mExecutorService;

    public AudioChannel(Pusher pusher) {
        mPusher = pusher;
        int channelConfig;
        if(channels == 2){
            channelConfig = AudioFormat.CHANNEL_IN_STEREO;
        }else{
            channelConfig = AudioFormat.CHANNEL_IN_MONO;
        }

        mExecutorService = Executors.newSingleThreadExecutor();

        // 音频编码器初始化
        pusher.initAudioEncoderNative(sampleRateInHz, channels);
        // (* 2) 避免容器溢出
        int minBufferSize = AudioRecord.getMinBufferSize(sampleRateInHz, channelConfig,
                AudioFormat.ENCODING_PCM_16BIT) * 2;

        // 获取编码器的输入样本数
        inputSamples = pusher.getInputSampleNative() * 2; // 16bit = 2字节

        audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, sampleRateInHz,
                channelConfig, AudioFormat.ENCODING_PCM_16BIT, Math.max(minBufferSize, inputSamples));

    }

    public void startLive() {
        isLive = true;
        mExecutorService.submit(new AudioTask());
    }

    public void stopLive() {
        isLive = false;
    }

    public void release() {
        if(audioRecord != null){
            audioRecord.release();
            audioRecord = null;
        }
    }

    class AudioTask implements Runnable{

        @Override
        public void run() {
            // 开始录音
            audioRecord.startRecording();
            byte[] data = new byte[inputSamples];
            // 每次读多少根据编码器的实际支持的输入样本数据大小来决定
            while(isLive){
                int length = audioRecord.read(data, 0, data.length);
                if(length > 0){
                    mPusher.pushAudioNative(data);
                }
            }
            audioRecord.stop(); // 停止
        }
    }
}
